<?php
/**
 * Each engineer has a duty to keep the code elegant
 * Created by wolffy.
 * Author @wolffy<13750088090@sina.cn>
 * Date: 2018/8/7
 * Time: 22:19
 */
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use League\OAuth2\Server\RequestTypes\AuthorizationRequest;
use Zend\Diactoros\Response as Psr7Response;
use Psr\Http\Message\ServerRequestInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\AuthorizationServer;


class AuthorizationsController extends Controller
{
//    public function store(AuthorizationRequest $request)
//    {
//        $username = $request->username;
//
//        filter_var($username, FILTER_VALIDATE_EMAIL) ?
//            $credentials['email'] = $username :
//            $credentials['phone'] = $username;
//
//        $credentials['password'] = $request->password;
//
//        if (!$token = Auth::guard('api')->attempt($credentials)) {
//            return $this->response->errorUnauthorized(trans('auth.failed'));
//        }
//
//        return $this->respondWithToken($token)->setStatusCode(201);
//    }

    public function store(AuthorizationRequest $originRequest, AuthorizationServer $server,
                          ServerRequestInterface $serverRequest)
    {
        try {
            return $server->respondToAccessTokenRequest($serverRequest, new Psr7Response)->withStatus(201);
        } catch(OAuthServerException $e) {
            dd($e->getMessage());
            return response()->errorUnauthorized($e->getMessage());
        }
    }

}